import {
  UserModel
} from '../../../models/user.js';

const userModel = new UserModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getAddressList();
  },

  getAddressList: function() {
    userModel.getAddressList().then(res => {
      if (res.errno === 0) {
        this.setData({
          addressList: res.data
        })
      }
    })
  },

  selectAddress: function(event) {
    // 选择收货地址 (用缓存的写法)
    // let idx = event.currentTarget.dataset.idx;
    // let addressList = this.data.addressList;
    
    // wx.setStorageSync('addressId', addressList[idx]);

    // wx.navigateTo({
    //   url: '/pages/shopping/checkout/index'
    // })

    let idx = event.currentTarget.dataset.idx;
    let _addressList = this.data.addressList;

    if (_addressList[idx].is_default) {
      _addressList[idx].is_default = _addressList[idx].is_default
    }
    else {
      _addressList[idx].is_default = !_addressList[idx].is_default
    }
    this.setData({
      addressList: _addressList
    });
    let p_id = this.data.addressList[idx].id;
    let p_name = this.data.addressList[idx].name;
    let p_mobile = this.data.addressList[idx].mobile;
    let p_province_id = this.data.addressList[idx].province_id;
    let p_city_id = this.data.addressList[idx].city_id;
    let p_district_id = this.data.addressList[idx].district_id;
    let p_address = this.data.addressList[idx].address;
    let p_is_default = this.data.addressList[idx].is_default;

    console.log(p_is_default)

    userModel.getAddressSave(p_id, p_name, p_mobile, p_province_id, p_city_id, p_district_id, p_address, p_is_default).then(res => {
      if (res.errno === 0) {
        wx.navigateBack({
          //url: '/pages/shopping/checkout/index'
          delta: 1
        })
      }
    })
  },

  addressAddOrUpdate: function(event) {
    wx.navigateTo({
      url: '/pages/shopping/addressAdd/index?id=' + event.currentTarget.dataset.addressId
    })
  }
})